<?php
	require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/engine/start.php");
	gatekeeper();
	$session = get_entity(get_input("chatsession"));
	$current_user = get_loggedin_user();

	$maxmembers = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, null, null, true);
	$members = get_entities_from_relationship("elggchat_session_member", $session->guid, null, null, null, null, null, $maxmembers);
	
	if(is_member($current_user->guid, $members)){
		remove_entity_relationship( $session->guid,"elggchat_session_member", get_loggedin_userid()); 
		
		$message = sprintf(elgg_echo('elggchat:action:leave'), $current_user->name);
		
		$session->annotate("elggchat_system_message", $message,ACCESS_LOGGED_IN,$current_user->guid);
	}
	
	if($session->countEntitiesFromRelationship("elggchat_session_member") == 0){
		$session->delete();
	}
?>